package com.wf.demo.job.util;

import java.io.*;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Auther: wf
 * @Date: 2019/12/11 10:58
 * @Description:
 */
public class DatabaseTool {
    public static void main(String[] args) {

        LocalDateTime currentDate =LocalDateTime.now();
        System.out.println("现在时间是"+ currentDate);
        String format="yyyy-MM-dd_HH-mm-ss";
        String sdfDate=currentDate.format(DateTimeFormatter.ofPattern(format));
        System.out.println("现在时间是"+ sdfDate);
        String fileNme = "test-" + sdfDate + ".sql"; //给test加上
        try {
            if (exportDatabase("127.0.0.1","3306","root","admin",
                    "e:\\beidouProject\\backupDatabase",fileNme,"how2java")
            ){
                System.out.println("数据库成功备份");
            }else {
                System.out.println("数据库备份失败");
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (importDatabase("127.0.0.1", "3306", "root", "admin",
                "e:\\beidouProject\\backupDatabase", "test-2019-12-10_17-51-26.sql", "how2java")) {
            System.out.println("数据库导入成功");
        } else {
            System.out.println("数据库导入失败");
        }
    }

    /**
     * Mysql数据库导出
     * @param hostIP 数据库地址
     * @param hostPort 端口
     * @param userName 用户名
     * @param password 密码
     * @param savePath 导出路径
     * @param fileName 导出文件名
     * @param databaseName 要导出数据库名
     * @return
     * @throws InterruptedException
     */
    public static boolean exportDatabase(String hostIP, String hostPort, String userName, String password, String savePath,
                                         String fileName, String databaseName) throws InterruptedException {
        //目录不存在则新建
        File saveFile = new File(savePath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }

        //在地址后补充系统默认分隔符
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }

        PrintWriter printWriter = null;

        BufferedReader bufferedReader = null;

        try {
            Runtime runtime = Runtime.getRuntime();

            //因为我的地址有空格，为解决找不到路径所以用了这个方式
            URL url = new URL("file:C:\\Program Files (x86)\\MySQL\\MySQL Server 5.5\\bin");
            String path = url.getPath();

            //"mysqldump -h127.0.0.1 -uroot -P3306 -padmin how2java"
            String cmd = "\\mysqldump -h" + hostIP + " -u" + userName + " -P" + hostPort + " -p" + password + " " + databaseName;

            cmd = path + cmd;
            Process process = runtime.exec(cmd);

            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);

            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            if (process.waitFor() == 0) {
                return true;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 导入Mysql数据库
     * @param hostIP 数据库地址
     * @param hostPort 端口
     * @param userName 用户名
     * @param password 密码
     * @param importFilePath 数据库文件路径
     * @param sqlFileName 要导入的文件名
     * @param databaseName 要导入的数据库名
     * @return
     * @throws InterruptedException
     */
    public static boolean importDatabase(String hostIP, String hostPort, String userName, String password, String importFilePath,
                                         String sqlFileName, String databaseName) {
        StringBuilder sb = new StringBuilder();
        sb.append("mysql");
        sb.append(" -h"+hostIP);
        sb.append(" -P"+hostPort);
        sb.append(" -u"+userName);
        sb.append(" -p"+password);
        sb.append(" "+databaseName+" <");
        sb.append(importFilePath+"\\"+sqlFileName);
        System.out.println("cmd命令为："+sb.toString());
        Runtime runtime = Runtime.getRuntime();
        System.out.println("开始还原数据");
        try {
            Process process = runtime.exec("cmd /c"+sb.toString());
            InputStream is = process.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is,"utf8"));
            String line = null;
            while ((line=bf.readLine())!=null){
                System.out.println(line);
            }
            is.close();
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        System.out.println("还原成功！");
        return  true;
    }
}
